package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;


    @Override
    @Transactional
    public Result queryList() {
        //1、从redis查询数据
        List<String> stringList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE_KEY, 0, -1);

        //2、如果拿到了直接返回
        if(!stringList.isEmpty()){
            List<Object> shopTypeList = stringList.stream().map((item) -> {
                return  JSONUtil.toBean(item,ShopType.class);
            }).collect(Collectors.toList());

            return Result.ok(shopTypeList);
        }

        //3、没有缓存，去mysql中查询
        List<ShopType> shopTypes = this.query().orderByAsc("sort").list();

        //4、查出来是空
        if(shopTypes.isEmpty()){
            return Result.fail("无此数据");
        }

        //5、弄成json串
        stringList= shopTypes.stream().map((item) -> {
            return  JSONUtil.toJsonStr(item);
        }).collect(Collectors.toList());


        //6、存进redis，设置一小时过期
        stringRedisTemplate.opsForList().leftPushAll(CACHE_SHOP_TYPE_KEY,stringList);
        stringRedisTemplate.expire(CACHE_SHOP_TYPE_KEY,1, TimeUnit.HOURS);

        return Result.ok(shopTypes);
    }
}
